package com.example.bookkeep.Mine;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import com.example.bookkeep.R;
import com.example.bookkeep.Utils.URLUtils;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class DataManageActivity extends AppCompatActivity {

    private Spinner spinnerYear, spinnerMonth;
    private Button btnExport;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_data_manage); // 注意文件名匹配你的 XML

        spinnerYear = findViewById(R.id.spinnerYear);
        spinnerMonth = findViewById(R.id.spinnerMonth);
        btnExport = findViewById(R.id.btnExportExcel);

        initSpinners();

        btnExport.setOnClickListener(v -> {
            String year = spinnerYear.getSelectedItem().toString();
            int monthPos = spinnerMonth.getSelectedItemPosition(); // 0表示未选
            String name = "账单" + year;
            String url = URLUtils.BASE_URL + "/bookKeep/export?year=" + year;
            if (monthPos > 0) {
                url += "&month=" + monthPos;
                name +=  "-" + monthPos;
            }

            // 从 SharedPreferences 获取 token
            SharedPreferences prefs = getSharedPreferences("auth", MODE_PRIVATE);
            String token = prefs.getString("token", "");

            System.out.println("token: " + token   +  "url : " +  url );
            downloadExcel(url, token,name);
        });
    }

    private void initSpinners() {
        int currentYear = Calendar.getInstance().get(Calendar.YEAR);
        List<String> years = new ArrayList<>();
        for (int i = currentYear; i >= currentYear - 10; i--) {
            years.add(String.valueOf(i));
        }

        ArrayAdapter<String> yearAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, years);
        spinnerYear.setAdapter(yearAdapter);

        List<String> months = new ArrayList<>();
        months.add("全部"); // 表示不选月
        for (int i = 1; i <= 12; i++) {
            months.add(String.valueOf(i));
        }

        ArrayAdapter<String> monthAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, months);
        spinnerMonth.setAdapter(monthAdapter);
    }

    private void downloadExcel(String url, String token,String name) {
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(url)
                .addHeader("Authorization", "Bearer " + token)
                .build();
        System.out.println("请求构建成功");
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> {
                    Toast.makeText(DataManageActivity.this, "导出失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                if (response.isSuccessful()) {
                    // 获取文件保存路径
                    File downloadsDir = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
                    String fileName = name + ".xlsx";
                    File file = new File(downloadsDir, fileName);

                    try (InputStream is = response.body().byteStream();
                         FileOutputStream fos = new FileOutputStream(file)) {

                        byte[] buffer = new byte[4096];
                        int len;
                        while ((len = is.read(buffer)) != -1) {
                            fos.write(buffer, 0, len);
                        }

                        runOnUiThread(() -> Toast.makeText(DataManageActivity.this, "导出成功，文件保存在:\n" + file.getAbsolutePath(), Toast.LENGTH_LONG).show());

                    } catch (Exception e) {
                        runOnUiThread(() -> Toast.makeText(DataManageActivity.this, "文件保存失败：" + e.getMessage(), Toast.LENGTH_SHORT).show());
                    }

                } else {
                    runOnUiThread(() -> Toast.makeText(DataManageActivity.this, "导出失败，服务器响应异常", Toast.LENGTH_SHORT).show());
                }
            }
        });
    }

}
